package com.blb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.entity.Categories;
import com.blb.entity.Product;
import com.blb.entity.ProductAttribute;
import com.blb.entity.User;
import com.blb.entity.page.BlbPage;
import com.blb.entity.page.DataTablePage;
import com.blb.service.ICategoriesService;
import com.blb.service.IProductService;
import com.blb.utils.ShiroUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HuaHao
 * @since 2019-11-16
 */
@Controller
@RequestMapping("/products")
public class ProductController {
    @Resource
    private IProductService iProductService;
    @Resource
    private ICategoriesService categoriesService;

 @RequiresPermissions("products_info")
    @RequestMapping("{page}")
    public String wel(@PathVariable String page){
        return "commodity/"+ page;
    }

    /*显示所有商品*/
    @ResponseBody
    @RequestMapping("findAllProduct")
    
    public BlbPage findAllProduct(@RequestParam(required = false, value ="pName") String pName, Integer start, Integer length){
        /*查询分页数据*/
        User user = ShiroUtils.getUser();
        IPage page = iProductService.page(new Page(start, length), new QueryWrapper<Product>().eq("company_id", user.getCompanyId()).like("p_name",pName));
        for(Object p:page.getRecords()){
            Product product = (Product) p;
            /*通过分类id查询分类名*/
            String categoriesName = categoriesService.categoriesName(product.getPEnterprise());
            product.setName(categoriesName);
        }
        /*查询总条数*/
        int count = iProductService.count(new QueryWrapper<Product>().eq("company_id", user.getCompanyId()).like("p_name",pName));
        return new DataTablePage(count,count,page.getRecords());
    }
    /*通过商品的id查询商品信息*/
    @RequestMapping("findOne")
    public String findOne(String id,Model model){
        Product product = iProductService.getOne(new QueryWrapper<Product>().eq("id", id));
        /*通过分类id查询分类名*/
        String name = categoriesService.categoriesName(product.getPEnterprise());
        product.setName(name);
        /*通过商品id查询自定义信息*/
        List<ProductAttribute> productAttributeList = iProductService.findProductAttributeList(id);
        product.setProductAttributeList(productAttributeList);
        System.out.println(product);
        model.addAttribute("product",product);
        return "commodity/editor.html";
    }

    @RequestMapping("addProduct")
    public String addProduct(Product product){
        System.out.println(product.getPImg());
        User user = ShiroUtils.getUser();
        String id = UUID.randomUUID().toString().replace("-", "");
        product.setId(id);
        product.setPAddtime(new Date());
        product.setCompanyId(user.getCompanyId());
        /*通过分类名查询分类id*/
        String cId = categoriesService.findCategoriesId(product.getName());
        product.setPEnterprise(cId);
        /*添加商品的基本信息*/
        iProductService.addProduct(product);
        /*添加商品的自定义信息*/
        if(!(product.getProductAttributeList().size()==1 && product.getProductAttributeList().get(0).getPNames()=="")){
            iProductService.addProductAttributeList(id,product.getProductAttributeList());
        }
        return "commodity/Products_info.html";
    }

    /**
     * 获取树的所有子节点，然后将值转换成list集合，然后查询出来一个List<>集合
     * @param nodeId
     * @param companyId
     * @param start
     * @param length
     * @return
     */
    /*@RequiresPermissions(value = {"apply", "audit"}, logical = Logical.OR)*/
    @ResponseBody
    @RequestMapping("/allNodes")
    public BlbPage getMyCompanyProInfo(@RequestParam(required = false,value = "nodeId")  String nodeId,@RequestParam(required = false,value = "companyId") String
            companyId,int start,int length){
        //查询我自己公司的商品
        User user = ShiroUtils.getUser();
        List<String> speIds = new ArrayList<>();
        List<Categories> allNode = categoriesService.getAllNode(nodeId,companyId);
        //如果他为子节点的时候，没有父ID时，就将自己放入去查询
        if (allNode.isEmpty()){
            speIds.add(nodeId);
            List<Product> list = iProductService.getMyCompanyProductInfo(speIds, companyId,start , length);
            return new DataTablePage(iProductService.count(speIds,companyId),iProductService.count(speIds,companyId),list);
        }
        List<String> ids = new ArrayList<>();
        for (Categories c : allNode){
            getChildren(c,ids);
        }
        ids.add(nodeId);
        List<Product> list = iProductService.getMyCompanyProductInfo(ids, companyId,start , length);
        return new DataTablePage(iProductService.count(ids,companyId),iProductService.count(ids,companyId),list);
    }

    /**
     * 将树获取到的一对多解迭代
     * @param categories
     * @param list
     */
    public void getChildren(Categories categories, List<String> list){
        list.add(categories.getId());
        if (categories.getProducts()!=null) {
            for (Categories c : categories.getProducts()) {
                getChildren(c, list);
            }
        }
    }

    @RequestMapping("updateProduct")
    public String updateProduct(Product product){
        System.out.println(product.getPImg());
        /*通过分类名查询分类id*/
        String cId = categoriesService.findCategoriesId(product.getName());
        product.setPEnterprise(cId);
        /*修改商品信息*/
        iProductService.updateProduct(product);
        /*修改自定义属性*/
        if(null!=product.getProductAttributeList()){
            for(int i=0;i<product.getProductAttributeList().size();i++){
                if(product.getProductAttributeList().get(i).getPNames()=="" || product.getProductAttributeList().get(i).getPNames()==null){
                    product.getProductAttributeList().remove(product.getProductAttributeList().get(i));
                }
            }
            /*删除自定义属性*/
            iProductService.deleteAttributeList(product.getId());
            /*添加自定义属性*/
            if(product.getProductAttributeList().size()!=0){
                iProductService.addProductAttributeList(product.getId(),product.getProductAttributeList());
            }
        }
        return "commodity/Products_info.html";
    }

    @RequestMapping("updatePstatus")
    @ResponseBody
    public String updatePstatus(String id,String status){
        System.out.println(status);
        iProductService.updatePstatus(id,status);
        return "123";
    }
    @RequestMapping("findNumber")
    @ResponseBody
    public String findNumber(String pNumber){
        User user = ShiroUtils.getUser();
        int count = iProductService.count(new QueryWrapper<Product>().eq("p_number", pNumber).eq("company_id",user.getCompanyId()));
        if(count==1){
            return "true";
        }else{
            return "false";
        }
    }
}

